PHP Tutorial
Decision making is anticipation of conditions occurring while execution of the program and specifying actions taken according to the conditions.
PHP programming language provides if, else, elseif, switch of decision making statements.
else condition can be optionally used to define an alternate block of statements to be executed if the boolean expression in the if condition is not true
If statement consists of a boolean expression followed by one or more statements.
The if...else statement executes some code if a condition is true and another code if that condition is false.
if (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
}
Let's put these syntax into real use.
<?php
$x = date("D");
if ($x == "Fri") {
echo "Code Now!";
} else {
echo "Code Always!";
}
?>
It will produce the following result −
Code Now!
The if...elseif...else statement executes different codes for more than two conditions..
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if first condition is false and this condition is true;
} else {
code to be executed if all conditions are false;
}
Let's put these syntax into real use.
<?php
$x = date("D");
if ($x == "Fri")
echo "Have a nice weekend!";
elseif ($x == "Sun")
echo "Have a nice Sunday!";
else
echo "Have a nice day!";
?>
It will produce the following result −
Have a nice Sunday!
The switch statement used to select one of many blocks of code to be executed.
switch (expression) {
case label1:
code to be executed if expression=label1;
break;
case label2:
code to be executed if expression=label2;
break;
case label3:
code to be executed if expression=label3;
break;
...
default:
code to be executed if expression is different from all labels;
}
Let's put these syntax into real use.
<?php
$x = date("D");
switch ($x){
case "Mon":
echo "Today is Monday";
break;
case "Tue":
echo "Today is Tuesday";
break;
case "Wed":
echo "Today is Wednesday";
break;
case "Thu":
echo "Today is Thursday";
break;
case "Fri":
echo "Today is Friday";
break;
case "Sat":
echo "Today is Saturday";
break;
case "Sun":
echo "Today is Sunday";
break;
default:
echo "Wonder which day is this ?";
}
?>
It will produce the following result −
Today is Sunday